package com.archie.zhufengfm.adapters;

/**
 * Created by Archie on 2015/10/21.
 */

import android.content.Context;
import android.content.DialogInterface;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ActionMenuView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.archie.zhufengfm.R;
import com.archie.zhufengfm.entity.discoverrecommend.AlbumRecommend;
import com.archie.zhufengfm.entity.discoverrecommend.ColumnsItem;
import com.archie.zhufengfm.entity.discoverrecommend.DiscoverRecommendAlbums;
import com.archie.zhufengfm.entity.discoverrecommend.DiscoverRecommendColumns;
import com.archie.zhufengfm.entity.discoverrecommend.DiscoverRecommendItem;
import com.archie.zhufengfm.entity.discoverrecommend.DiscoverRecommendSpecial;
import com.archie.zhufengfm.entity.discoverrecommend.SpecialItem;
import com.archie.zhufengfm.widgets.SpecialItemView;
import com.squareup.picasso.Picasso;

import java.lang.reflect.Field;
import java.util.List;

/**
 * 发现推荐部分的 ListView Adapter
 * 支持多布局的复用；
 */
public class DiscoverRecommendAdapter extends BaseAdapter {

    private Context context;
    private List<DiscoverRecommendItem> items;

    // -------------------------------------------------------

    // 点击事件处理器, 推荐专辑的点击事件
    private View.OnClickListener onRecommendAlbumClickListener;

    public void setOnRecommendAlbumClickListener(View.OnClickListener onRecommendAlbumClickListener) {
        this.onRecommendAlbumClickListener = onRecommendAlbumClickListener;
    }
    // -------------------------------------------------------

    public DiscoverRecommendAdapter(Context context, List<DiscoverRecommendItem> items) {
        this.context = context;
        this.items = items;
    }

    @Override
    public int getCount() {
        int ret = 0;

        if(items != null){
            ret = items.size();
        }

        return ret;
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public int getViewTypeCount() {
        return 3;
    }

    @Override
    public int getItemViewType(int position) {
        int ret = 0;

        DiscoverRecommendItem item = items.get(position);

        if(item instanceof DiscoverRecommendAlbums){// 小编推荐，热门推荐

            ret = 2;

        }else if(item instanceof DiscoverRecommendColumns){// 发现新奇

            ret = 1;

        }else if(item instanceof DiscoverRecommendSpecial){// 精品听单

            ret = 0;

        }

        return ret;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View ret = null;

        // 1. 获取数据
        DiscoverRecommendItem item = items.get(position);

        if(item instanceof DiscoverRecommendAlbums){// 小编推荐，热门推荐

            ret = bindAlbumsView(position, convertView, parent);

        }else if(item instanceof DiscoverRecommendSpecial){
            // 精品听单

            ret = bindSpecialView(position, convertView, parent);

        }else if(item instanceof DiscoverRecommendColumns){

            // 发现新奇
            ret = bindColumnView(position, convertView, parent);

        }

        return ret;
    }

    /**
     * 加载 专辑推荐的 Item ：小编推荐 和 热门推荐
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    private View bindAlbumsView(int position, View convertView, ViewGroup parent){
        View ret = null;

        // 复用
        if (convertView != null) {

            ret = convertView;

        }else {

            LayoutInflater inflater = LayoutInflater.from(context);

            ret = inflater.inflate(
                    R.layout.discover_recommend_album_item,
                    parent,
                    false);

        }

        // 2. ViewHolder
        AlbumViewHolder holder = (AlbumViewHolder) ret.getTag();

        if (holder == null) {

            holder = new AlbumViewHolder();

            holder.txtTitle = (TextView) ret.findViewById(R.id.recommend_album_title);
            holder.txtMore = (TextView) ret.findViewById(R.id.recommend_album_more);

            // TODO 点击more，进入推荐列表


            holder.albumIcons = new ImageView[3];
            holder.albumNames = new TextView[3];
            holder.trackNames = new TextView[3];

            for (int i = 0; i < 3; i++) {

                // 给 Holder 设置数组的内容
                holder.albumIcons[i] =
                        (ImageView) findView(ret, "recommend_album_icon_" + i);

                // TODO 点击专辑图片，进入专辑详情
                holder.albumIcons[i].setOnClickListener(onRecommendAlbumClickListener);

                holder.albumNames[i] =
                        (TextView) findView(ret, "recommend_album_name_" + i);

                holder.trackNames[i] =
                        (TextView) findView(ret, "recommend_album_track_name_"+ i);
            }

            ret.setTag(holder);
        }

        // 3. 获取数据、设置内容
        DiscoverRecommendAlbums albums =
                (DiscoverRecommendAlbums) items.get(position);

        String title = albums.getTitle();

        holder.txtTitle.setText(title);

        // 处理 “更多”
        boolean hasMore = albums.isHasMore();
        if (hasMore){
            holder.txtMore.setVisibility(View.VISIBLE);
        }else{
            holder.txtMore.setVisibility(View.INVISIBLE);
        }

        // 处理专辑标题
        List<AlbumRecommend> albumRecommends = albums.getAlbumRecommends();

        int len = holder.albumIcons.length;

        if (albumRecommends != null) {


            for (int i = 0; i < len; i++) {

                AlbumRecommend albumRecommend = albumRecommends.get(i);

                title = albumRecommend.getTitle();

                holder.albumNames[i].setText(title);

                title = albumRecommend.getTrackTitle();

                holder.trackNames[i].setText(title);

                // 使用 Picasso 加载图片
                String coverLarge = albumRecommend.getCoverLarge();

                ImageView imageView = holder.albumIcons[i];

                // 把对象作为标识传给imageView
                imageView.setTag(albumRecommend);

                Picasso.with(context)
                        .load(coverLarge)
                        .placeholder(R.mipmap.image_default_album_s)
                        .error(R.mipmap.image_default_album_s)
                        .into(holder.albumIcons[i]);


            }

        }

        return ret;
    }

    /**
     * 加载 发现新奇
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    private View bindColumnView(int position, View convertView, ViewGroup parent){
        View ret = null;

        if (convertView != null) {

            ret = convertView;

        }else{

            LayoutInflater inflater = LayoutInflater.from(context);
            ret = inflater.inflate(R.layout.discover_recommend_columns_item, parent, false);

        }

        // 2.ViewHolder 处理
        SpecialAndColumnsViewHolder holder = (SpecialAndColumnsViewHolder) ret.getTag();

        if (holder == null) {

            holder = new SpecialAndColumnsViewHolder();

            holder.txtTitle = (TextView) ret.findViewById(R.id.recommend_columns_title);

            holder.txtMore = (TextView) ret.findViewById(R.id.recommend_columns_more);

            holder.itemContainer = (LinearLayout) ret.findViewById(R.id.recommend_columns_container);

            ret.setTag(holder);

        }

        // 3. 获取数据
        DiscoverRecommendItem discoverRecommendItem = items.get(position);

        String title = "";

        boolean hasMore = false;

        title = discoverRecommendItem.getTitle();

        hasMore = discoverRecommendItem.isHasMore();

        holder.txtTitle.setText(title);

        if(hasMore){

            holder.txtMore.setVisibility(View.VISIBLE);

        }else{

            holder.txtMore.setVisibility(View.INVISIBLE);

        }

        // 3.1 清空旧的 LinearLayout 数据，再根据听单的item来添加
        holder.itemContainer.removeAllViews();

        if (discoverRecommendItem instanceof DiscoverRecommendColumns) {

            DiscoverRecommendColumns discoverRecommendColumns = (DiscoverRecommendColumns) discoverRecommendItem;

            List<ColumnsItem> columnsItems = discoverRecommendColumns.getColumnsItems();

            if (columnsItems != null) {

                int itemCount = columnsItems.size();

                for (int i = 0; i < itemCount; i++) {

                    View view = getColumnView(parent);

                    LinearLayout.LayoutParams lp =
                            new LinearLayout.LayoutParams(
                                    ViewGroup.LayoutParams.MATCH_PARENT,
                                    ViewGroup.LayoutParams.WRAP_CONTENT
                            );

                    view.setLayoutParams(lp);

                    holder.itemContainer.addView(view);

                    ColumnViewHolder columnHolder = (ColumnViewHolder) view.getTag();;

                    ColumnsItem columnsItem = columnsItems.get(i);

                    // 设置点击监听
                    view.setOnClickListener(onRecommendAlbumClickListener);
                    // 给监听添加对象标识，传递对象
                    view.setTag(columnsItem);

                    columnHolder.columnTitle.setText(columnsItem.getTitle());

                    columnHolder.columnSubtitle.setText(columnsItem.getSubtitle());

                    String coverPath = columnsItem.getCoverPath();

                    // 加载图片
                    Picasso.with(context).load(coverPath)
                            .placeholder(R.mipmap.image_default_album_s)
                            .error(R.mipmap.image_default_album_s)
                            .into(columnHolder.columnIcon);

                    if(i == itemCount - 1)

                        columnHolder.columnImgLine.setVisibility(View.INVISIBLE);

                }

            }

        }

        return ret;
    }

    /**
     * 发现新奇加载column的的单个View
     * @return
     */
    private View getColumnView(ViewGroup parent){

        View view = LayoutInflater.from(context).inflate(R.layout.discover_recommend_columns_item_column, parent, false);

        ColumnViewHolder columnViewHolder = new ColumnViewHolder();

        columnViewHolder.columnIcon =
                (ImageView) view.findViewById(R.id.discover_recommend_columns_item_column_icon);

        columnViewHolder.columnTitle =
                (TextView) view.findViewById(R.id.discover_recommend_columns_item_column_title);

        columnViewHolder.columnSubtitle =
                (TextView) view.findViewById(R.id.discover_recommend_columns_item_column_subtitle);

        columnViewHolder.columnImgLine =
                (ImageView) view.findViewById(R.id.discover_recommend_columns_item_column_img_line);

        view.setTag(columnViewHolder);

        return view;
    }

    /**
     * 加载 精品听单, 发现新奇，布局复用
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    private View bindSpecialView(int position, View convertView, ViewGroup parent){
        View ret = null;

        // 1. 复用
        if (convertView != null) {

            ret = convertView;

        }else{

            LayoutInflater inflater = LayoutInflater.from(context);
            ret = inflater.inflate(R.layout.discover_recommend_special_item, parent, false);

        }

        // 2.ViewHolder 处理
        SpecialAndColumnsViewHolder holder = (SpecialAndColumnsViewHolder) ret.getTag();

        if (holder == null) {

            holder = new SpecialAndColumnsViewHolder();

            holder.txtTitle = (TextView) ret.findViewById(R.id.recommend_special_title);

            holder.txtMore = (TextView) ret.findViewById(R.id.recommend_special_more);

            holder.itemContainer = (LinearLayout) ret.findViewById(R.id.recommend_special_container);

            ret.setTag(holder);

        }

        // 3. 获取数据，显示数据
        DiscoverRecommendItem discoverRecommendItem = items.get(position);

        String title = "";

        boolean hasMore = false;

        title = discoverRecommendItem.getTitle();

        hasMore = discoverRecommendItem.isHasMore();

        holder.txtTitle.setText(title);

        if(hasMore){

            holder.txtMore.setVisibility(View.VISIBLE);

        }else{

            holder.txtMore.setVisibility(View.INVISIBLE);

        }

        // 3.1 清空旧的 LinearLayout 数据，再根据听单的item来添加
        holder.itemContainer.removeAllViews();

        if (discoverRecommendItem instanceof DiscoverRecommendSpecial) {

            DiscoverRecommendSpecial special =
                    (DiscoverRecommendSpecial) discoverRecommendItem;

            List<SpecialItem> specialItems = special.getSpecialItems();

            if (specialItems != null) {

                int index = -1;
                int itemCount = specialItems.size();

                for (SpecialItem specialItem : specialItems) {

                    index++;

                    // 创建自定义 View，用来显示听单信息
                    SpecialItemView itemView = new SpecialItemView(context);

                    // 给单项设置监听
                    itemView.setOnClickListener(onRecommendAlbumClickListener);
                    // 设置标识，传递对象
                    itemView.setTag(specialItem);

                    LinearLayout.LayoutParams lp =
                            new LinearLayout.LayoutParams(
                                    ViewGroup.LayoutParams.MATCH_PARENT,
                                    ViewGroup.LayoutParams.WRAP_CONTENT
                            );

                    itemView.setLayoutParams(lp);

                    holder.itemContainer.addView(itemView);

                    // 设置听单的内容
                    itemView.setTitle(specialItem.getTitle());

                    itemView.setSubtitle(specialItem.getSubtitle());

                    itemView.setNumber(specialItem.getFootnote());

                    itemView.setShowBottomLine(true);

                    // 获取听单的图标
                    ImageView imageView = itemView.getImgIcon();

                    String coverPath = specialItem.getCoverPath();

                    // 加载图片
                    Picasso.with(context).load(coverPath)
                            .placeholder(R.mipmap.image_default_album_s)
                            .error(R.mipmap.image_default_album_s)
                            .into(imageView);

                    // 判断是否是最后一个
                    if (index == itemCount - 1) {

                        itemView.setShowBottomLine(false);

                    }

                }
            }
        }

        return ret;
    }

    /**
     * 利用类的反射，来获取指定的 R.id.XXX 代表的 View
     * @param container
     * @param fieldName
     * @return
     */
    public static View findView(View container, String fieldName){
        View ret = null;

        if (container != null && fieldName != null) {

            Class<R.id> idClass = R.id.class;
            try {

                Field field = idClass.getDeclaredField(fieldName);

                int id = field.getInt(idClass);

                // 通过静态常亮，获取int值，来查找 View
                ret = container.findViewById(id);

            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return ret;
    }

    /**
     * 发现新奇 中 具体column项的holder
     */
    private static class ColumnViewHolder{

        public ImageView columnIcon, columnImgLine;

        public TextView columnTitle, columnSubtitle;

    }

    /**
     * 精品听单/发现新奇 公用 ViewHolder
     */
    private static class SpecialAndColumnsViewHolder{

        public TextView txtTitle, txtMore;

        // 存储 SpecialItemView
        public LinearLayout itemContainer;

    }

    /**
     * 小编推荐的ViewHolder
     */
    private static class AlbumViewHolder{

        public TextView txtTitle, txtMore;

        // 三张图片，在不同的RelativeLayout
        public ImageView[] albumIcons;

        // 三个专辑标题，曲目名称
        public TextView[] albumNames, trackNames;

    }

}
